//
//  CHJSpeedCount.m
//  CHJVideoKit_Example
//
//  Created by jiaxuzhou on 2017/12/2.
//  Copyright © 2017年 jxzjxz. All rights reserved.
//

#import "CHJSpeedCount.h"

time_t time(time_t *);

#define min(a,b) ((a)<(b)?(a):(b))

@implementation CHJSpeedCount

- (id)init {
    self = [super init];
    if (self) {
        [self reset];
    }
    return self;
}

- (void)reset {
    m_firstts = 0;
    m_lastts = 0;
    m_lastspeed = 0;
    m_lastspeedval = 0;
}

- (void)adddata:(int)len {
    unsigned int now = (unsigned int) time(NULL);
    if (now - m_lastts >= 10) {
        memset(m_counting, 0, sizeof(m_counting));
        m_lastts = now;
    } else {
        while (m_lastts + 1 <= now) {
            m_counting[(m_lastts + 1) % 10] = 0;
            m_lastts++;
        }
    }
    if (!m_firstts)
        m_firstts = now - 1;
    m_counting[now % 10] += len;
}

- (unsigned int)getspeed {
    unsigned int now = (unsigned int) time(NULL);
    if (now != m_lastspeed) {
        [self adddata:0];
        m_lastspeed = now;
        unsigned int sum = 0, i;
        for (i = 0; i < 10; i++)
            sum += m_counting[i];
        i = min((unsigned int) 10, now - m_firstts);
        m_lastspeedval = sum / i;
    }
    return m_lastspeedval;
}


@end
